use std::fs;
use std::path::Path;

fn main() {
    let python_dir = "lib/python/env";
    let target_dir = if cfg!(debug_assertions) {
        "target/debug" // Debug 模式
    } else {
        "target/release" // Release 模式
    };

    // 检查 Python 环境目录是否存在
    if Path::new(python_dir).exists() {
        println!(
            "Copying Python environment from {} to {}",
            python_dir, target_dir
        );

        // 创建目标目录
        fs::create_dir_all(target_dir).unwrap();

        // 遍历 Python 环境目录并复制文件
        for entry in fs::read_dir(python_dir).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

            // 跳过某些文件或路径
            if should_skip(&file_name) {
                println!("Skipping: {}", file_name);
                continue;
            }

            let dest = Path::new(target_dir).join(&file_name);

            // 如果是目录，递归复制
            if path.is_dir() {
                copy_dir_all(&path, &dest).unwrap();
            } else {
                // 如果是文件，直接复制
                fs::copy(&path, &dest).unwrap();
                println!("Copied: {}", file_name);
            }
        }
    } else {
        println!("Python environment directory not found: {}", python_dir);
    }
}

// 递归复制目录
fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let path = entry.path();
        let file_name = path.file_name().unwrap().to_str().unwrap().to_string();

        // 跳过某些文件或路径
        if should_skip(&file_name) {
            println!("Skipping: {}", file_name);
            continue;
        }

        let dest = dst.join(&file_name);

        if path.is_dir() {
            copy_dir_all(&path, &dest)?;
        } else {
            fs::copy(&path, &dest)?;
            println!("Copied: {}", file_name);
        }
    }
    Ok(())
}

// 判断是否应该跳过该文件或目录
fn should_skip(file_name: &str) -> bool {
    file_name == "python3.dll"
        || file_name == "Scripts"
        || file_name == "tcl"
        || file_name == "Tools"
        || file_name == "tkinter"
        || file_name == "Doc"
        || file_name == "code"
        || file_name.ends_with(".exe")
}
